var win = Titanium.UI.getCurrentWindow();
var currentDir = null;
var errorStates = [];

$(document).ready(function() {

	var defaultFolder = getProp('defaultFolder',true);
	var defaultFile = getProp('defaultFile',false);
	if ( defaultFolder && defaultFile ) {
		currentDir = Titanium.Filesystem.getFile(defaultFolder);
   
     	
     	$('h1').text('Overzicht langstdurende errors in bestand ' + defaultFile );
     	
     	$('#kies').bind('click', function() {
     		$('#files').children().remove();
			showFiles();
			$('#files').fadeIn('slow');
		});
		
		readTheFile(defaultFile);	
	}
	else
		showFiles();	
});

function getProp(prop, esc) {
	var props = Titanium.App.Properties.listProperties();
	for (var c=0;c<props.length;c++)
	{
    	var value = Titanium.App.Properties.getString(props[c]);
    	if (props[c] == prop )
    		return esc ? unescape(value) : value;
	}	
	return false;
}


function showFiles() {	
   win.openFolderChooserDialog(function(folderResponse) {
      var file = Titanium.Filesystem.getFile(folderResponse[0]);
      Titanium.App.Properties.setString("defaultFolder",escape(folderResponse[0]));
      currentDir = file;
      var listing = file.getDirectoryListing();
      for (var i = 0; i < listing.length; i++) {
      	if (!listing[i].isDirectory())
      		$('#files').append('<li id="file_'+ listing[i].name() +'">' + listing[i].name() + '</li>');
      }
      $('li[id*=file_]').bind('mouseover', function() {
      	$(this).css('background-color','#abc');
      });
      $('li[id*=file_]').bind('mouseout', function() {
      	$(this).css('background-color','#fff');
      });
      
     $('li[id*=file_]').bind('click', function() {
      	$('h1').text('Overzicht langstdurende errors in bestand ' + $(this).attr('id').split('_')[1]);
      	Titanium.App.Properties.setString("defaultFile", $(this).attr('id').split('_')[1]);
      	readTheFile( $(this).attr('id').split('_')[1] );
      	$('#files').fadeOut('slow');
      });
      

   });
}


function readTheFile(filename) {
   var line;
   var userDir = currentDir; //Titanium.Filesystem.getUserDirectory();
   var readFile = Titanium.Filesystem.getFile(userDir, filename);
   if (readFile.exists()){
   	 $('#content').find('table').remove();
   	 $('#content').append("<table id='top10' class='tablesorter' ></table>");

      errorStates = [];
      $('#top10').children().remove();      
      $('#top10').append("<thead><tr><th>Start</th><th>Einde</th><th>Tekst</th><th>Duur (sec)</th><th>Duur</th></tr></thead>");					    
											
      var readStream = Titanium.Filesystem.getFileStream(readFile);
      readStream.open(Titanium.Filesystem.MODE_READ);
      while ( line = readStream.readLine()) {
      	 var regel = line + '';
      	 var cols = regel.split(';');

		 //indien error status is opgeheven
      	 if ( cols[2] =='0' ) {
      	 	var errInd = getActErrInd(cols[4]);
      	 	if (errInd > 0) {
      	 		errorStates[errInd].einde = cols[13];
      	 		var d = cols[13].split(' ');
      	 		var x = d[0].split('.');
      	 		var y = d[1].split(':');
      	 		var endDate = new Date(x[2],x[1],x[0],y[0],y[1],y[2]);      	 		
      	  		errorStates[errInd].duur =(endDate.getTime() - errorStates[errInd].startDate.getTime())/ 1000;
      	 		errorStates[errInd].duurObj = secondsToTime( (endDate.getTime() - errorStates[errInd].startDate.getTime())/ 1000 ); 
      	 		errorStates[errInd].sts = 0;     	 		
      	 	}
      	 } else {
      	 	if (cols[2]=='1') {
			//error status is nog actief of actief geworden
      	 		if (getActErrInd(cols[4])== -1) {
	      	 		//geen actieve errorstatus gevonden dus nieuwe toevoegen
	      	 		//alert(cols[13]);
					startTime = cols[13];
	      	 		var d = startTime.split(' ');
	      	 		var x = d[0].split('.');
	      	 		var y = d[1].split(':');
	      	 		var startDate = new Date(x[2],x[1],x[0],y[0],y[1],y[2]);
	      	 		errorStates.push({start: startTime, einde: startTime, tekst: cols[14], plc: cols[15], duur: 0, duurObj: {}, msgNo: cols[4], sts: 1, startDate: startDate });    	 		
      	 		}      	 		
      	 	} else ; // niks doen
      	 }
      }
      readStream.close();
      
      var i = 0;
      while (i<errorStates.length) {
      		$('#top10').append('<tr><td>' + errorStates[i].start + '</td><td>'+ errorStates[i].einde +'</td><td>'+ errorStates[i].tekst + '</td><td>' + errorStates[i].duur +  '</td><td>' + errorStates[i].duurObj.h + ':' + errorStates[i].duurObj.m + ':' +errorStates[i].duurObj.s + '</td></tr>' );
      	i++;
     }
     //$('#top10').fadeIn('slow');
   	 $("#top10").tablesorter({sortList:[[3,1]]});
     //$("table").trigger("sorton",[[3,1]]);
   }
   else {
   		alert('Could not open file');
   }
   	
}

//Actieve errorstate index ophalen
function getActErrInd(err) {
	var i = errorStates.length-1;
	while (i >= 0) {
		if (errorStates[i].msgNo == err && errorStates[i].sts == 1)
			return i;
		i--;
	}
	return -1;
}

function secondsToTime(secs)
{
    var hours = Math.floor(secs / (60 * 60));   
    var divisor_for_minutes = secs % (60 * 60);
    var minutes = Math.floor(divisor_for_minutes / 60);
 
    var divisor_for_seconds = divisor_for_minutes % 60;
    var seconds = Math.ceil(divisor_for_seconds);
   
    var obj = {
        "h": hours<10 ? '0'+hours : hours+'',
        "m": minutes<10 ? '0'+minutes : minutes+'',
        "s": seconds<10 ? '0'+seconds : seconds+''
    };
    return obj;
}
